package com.sgb.businessmodule.view.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.library.baseAdapters.BR;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.businessmodule.R;
import com.sgb.businessmodule.databinding.FragmentHomeBusinessOpportunitiesBinding;
import com.sgb.businessmodule.entity.NotifyRefreshEvent;
import com.sgb.businessmodule.view.ui.activity.BusinessOpportunityHallActivity;
import com.sgb.businessmodule.viewmodel.HomeBusinessOpportunitiesModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.refresh.SuperSwipeRefreshLayout;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.countmenu.CountMenuEntity;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.view.weiget.CountMenuView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * @author 张驰
 * @date 2021/8/5 13:29
 * @Description 商机首页界面
 */
@Route(path = AppRouteConstant.ShangJi.ROUTER_PATH_SJ_HOME)
public class HomeBusinessOpportunitiesFragment extends AppLazyFragment implements SuperSwipeRefreshLayout.OnPullRefreshListener {
    private FragmentHomeBusinessOpportunitiesBinding mBinding;
    private HomeBusinessOpportunitiesModel mViewModel;

    private String[] titles = {"最新商机"};

    private TextView textView;

    public static HomeBusinessOpportunitiesFragment newInstance() {
        HomeBusinessOpportunitiesFragment fragment = new HomeBusinessOpportunitiesFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_home_business_opportunities, container, false);
        mViewModel = new ViewModelProvider(this).get(HomeBusinessOpportunitiesModel.class);
        mBinding.swipeRefresh.setHeaderView(createHeaderView());
        mBinding.appBarLayout.addOnOffsetChangedListener((appBarLayout, i) -> mBinding.swipeRefresh.setEnabled(i >= 0));
        mBinding.swipeRefresh.setOnPullRefreshListener(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        mViewModel.countMenuList.observe(this, new Observer<List<CountMenuEntity>>() {
            @Override
            public void onChanged(List<CountMenuEntity> list) {
                initMenuView(list);
            }
        });
    }

    private void initMenuView(List<CountMenuEntity> list) {
        List<MenuEntity> menuEntityList = new ArrayList<>();
        for (CountMenuEntity countMenuEntity:list ){
            MenuEntity menuEntity = new MenuEntity();
            menuEntity.setAppIcon(countMenuEntity.getAppIcon());
            menuEntity.setAppIconUrl(countMenuEntity.getAppIconUrl());
            menuEntity.setId(countMenuEntity.getId());
            menuEntity.setSelected(countMenuEntity.isSelected());
            menuEntity.setName(countMenuEntity.getName());
            menuEntityList.add(menuEntity);
        }

        mBinding.calendarMenuView.initData(getChildFragmentManager(), menuEntityList, new CountMenuView.OnItemClick() {

            @Override
            public void onItemClick(MenuEntity entity, int position, int num) {
                if (isAuth()) {
                    if (entity.getName().equals("查看更多")) {
                        BusinessOpportunityHallActivity.start(getActivity(), 0, "");
                    } else {
                        BusinessOpportunityHallActivity.start(getActivity(), position + 1, entity.getId());
                    }
                }
            }
        });
    }

    private void initTabLayout() {
        ArrayList<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(HomeBusinessChildFragment.newInstance());
        SlidingFragmentPagerAdapter mPagerAdapter = new SlidingFragmentPagerAdapter(getChildFragmentManager(), fragmentList, titles);
        mBinding.viewPager.setAdapter(mPagerAdapter);
        mBinding.tabLayout.setupWithViewPager(mBinding.viewPager);
    }

    @Override
    protected void onLazyLoad() {
        //获取商机首页顶部菜单栏
        mViewModel.requestBusinessMenuData();

        //获取Tab菜单栏
        initTabLayout();
    }

    @Override
    public void onVisible() {
        super.onVisible();
    }

    private View createHeaderView() {
        @SuppressLint("InflateParams")
        View headerView = LayoutInflater.from(mBinding.swipeRefresh.getContext()).inflate(R.layout.super_swipe_refresh_head, null);
        ProgressBar progressBar = headerView.findViewById(R.id.pb_view);
        textView = headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    @SuppressLint({"AutoDispose", "CheckResult"})
    @Override
    public void onRefresh() {
        textView.setText("正在刷新");
        Observable.timer(1500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    EventBus.getDefault().post(new NotifyRefreshEvent(true));
                    //获取商机首页顶部菜单栏
                    mViewModel.requestBusinessMenuData();
                    mBinding.swipeRefresh.setRefreshing(false);
                });
    }

    @Override
    public void onPullDistance(int distance) {

    }

    @Override
    public void onPullEnable(boolean enable) {
        textView.setText(enable ? "释放立即刷新" : "下拉刷新");
    }

    /**
     * 商机信息查看权限判断
     *
     * @return ture 符合权限要求 false 否
     */
    public boolean isAuth() {
        List<String> authCompanyList = new ArrayList<>();
        authCompanyList.add("202004302544834");
        authCompanyList.add("1316637963131686912");
        authCompanyList.add("1321724009720713216");
        authCompanyList.add("202007211619262");
        authCompanyList.add("202004302544834");
        authCompanyList.add("202008148048453");
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if (type == 1) {
                String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                if (authCompanyList.contains(companyNo)) {
                    return true;
                } else {
                    MToast.showToast(getActivity(), "功能开发中，敬请期待");
                }
            } else {
                MToast.showToast(getActivity(), "功能开发中，敬请期待");
            }
        } else {
            MToast.showToast(getActivity(), "功能开发中，敬请期待");
        }
        return false;
    }
}
